//
//  DLAlipayPayOrAuthToolsShareManager.m
//  DLSharePaySDK
//
//  Created by Dracy on 2019/8/20.
//  Copyright © 2019 dl_hzk. All rights reserved.
//

#import "DLAlipayPayOrAuthToolsManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import <CommonCrypto/CommonDigest.h>

/**
 *
 *  此处必须保证在Info.plist 中的 URL Types 的 Identifier 对应一致
 */
#define ZhiFuBaoTypeUrl @"zhifubao"

DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterAPPIDKey = @"appid";
DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterRetcodeKey = @"retcode";
DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterPrepayIDKey = @"prepay_id";
DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterNonceStrKey = @"nonce_str";
DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterPackageKey = @"package";
DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterPartnerIDKey = @"partnerid";
DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterTimestampKey = @"timestamp";
DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterBussinessAPIKey = @"bussiness_api_key";

DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterOrderRequestStringKey = @"order_request_string";
//DLAlipayPayToolsParameterKey const DLAlipayPayToolsParameterAPPSchemeKey = @"dlappmerchant";

@interface DLAlipayPayOrAuthToolsManager()

@property (nonatomic, copy) void (^responseBlock)(NSDictionary *, NSError *);
@property (nonatomic,copy) DLAlipayPayManagerBack payBack;

@end

@implementation DLAlipayPayOrAuthToolsManager

+ (instancetype)sharedInstance
{
    static DLAlipayPayOrAuthToolsManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[DLAlipayPayOrAuthToolsManager alloc] init];
    });
    return _sharedInstance;
}

#pragma mark - 通用

+ (BOOL)dl_isHandlePayURL:(NSURL *)theURL
{
    
    if ([theURL.host isEqualToString:@"safepay"])
    {//阿里支付
        return YES;
    }
    
    return NO;
}

- (BOOL)dl_handleOpenURL:(NSURL *)theURL{
    return [self dl_handleOpenURL:theURL universalLink:nil];
}

- (BOOL)dl_handleOpenURL:(NSURL *)theURL universalLink:(NSUserActivity *)userActivity
{
    if ([theURL.host isEqualToString:@"safepay"])
    {//阿里支付
        return [self AlipayHandleOpenURL:theURL];
    }
    
    return NO;
}

#pragma mark -
#pragma mark - 支付宝相关

- (void)dl_AlipayPayWithParameters:(NSDictionary <DLAlipayPayToolsParameterKey, id> *)theParam schemeKey:(NSString *)schemeKey response:(nonnull void (^)(NSDictionary * _Nullable, NSError * _Nullable))theResponse
{
    self.responseBlock = theResponse;
    
    if (theParam[DLAlipayPayToolsParameterOrderRequestStringKey])
    {
        __weak typeof(self) weakSelf = self;
        
        //调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:theParam[DLAlipayPayToolsParameterOrderRequestStringKey] fromScheme:schemeKey callback:^(NSDictionary *resultDic) {
            
            NSLog(@"reslut = %@ - %@",resultDic, resultDic[@"memo"]);
            
            __strong typeof(weakSelf) strongSelf = weakSelf;
            
            if (strongSelf.responseBlock)
            {
                strongSelf.responseBlock(resultDic, nil);
            }
        }];
    }
}

- (BOOL)AlipayHandleOpenURL:(NSURL *)theUrl
{
    __weak typeof(self) weakSelf = self;
    
    [[AlipaySDK defaultService]processOrderWithPaymentResult:theUrl standbyCallback:^(NSDictionary *resultDic) {
        
        NSLog(@"result = %@ - %@", resultDic, resultDic[@"memo"]);
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        if (strongSelf.responseBlock)
        {
            strongSelf.responseBlock(resultDic, nil);
        }
    }];
    
    // 授权跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService]processAuth_V2Result:theUrl standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@", resultDic);
        // 解析 auth code
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        NSString *result = resultDic[@"result"];
        NSString *authCode = nil;
        if (result.length > 0)
        {
            NSArray *resultArr = [result componentsSeparatedByString:@"&"];
            
            for (NSString *subResult in resultArr)
            {
                if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="])
                {
                    authCode = [subResult substringFromIndex:10];
                    break;
                }
            }
        }
        NSLog(@"授权结果 authCode = %@", authCode ?: @"");
        
        if (strongSelf.responseBlock)
        {
            strongSelf.responseBlock(resultDic, nil);
        }
    }];
    
    return YES;
}

/*
 微信/支付宝授权
 */
- (void)dl_AlipayWithAuthParameter:(id)parameter schemeKey:(NSString *)schemeKey callBack:(DLAlipayPayManagerBack)payBack{
    NSAssert(parameter, @"订单信息不能为空");
    // 发起支付
    self.payBack = payBack;
    if ([parameter isKindOfClass:[NSString class]]){
        
        [[AlipaySDK defaultService] auth_V2WithInfo:parameter fromScheme:schemeKey
                                           callback:^(NSDictionary *resultDic) {
                                               NSLog(@"result = %@",resultDic);
                                               
                                               NSString * code=resultDic[@"resultStatus"];
                                               if (![code isEqualToString:@"9000"]) {
                                                   //失败
                                               }else{
                                                   //成功
                                               }
                                               if (self.payBack) {
                                                   self.payBack(resultDic);
                                               }
                                           }];
    }
}

@end
